import React, { PureComponent } from "react";
import { connect } from "react-redux";

// 样式化组件
import { HomeWrapper, HomeLeft, HomeRight, BackTop } from "./style";
// 子组件
import Topic from "./components/Topic";
import List from "./components/List";
import Recommend from "./components/Recommend";
import Writer from "./components/Writer";
// 数据
import * as actionCreators from "./store/actionCreators";

class Home extends PureComponent {
    constructor(props) {
        super(props);
    }

    handleScrollTop = () => {
        window.scrollTo(0, 0);
    };

    bindEvents = () => {
        window.addEventListener("scroll", this.props.changeScrollTopShow);
    };

    render() {
        const { showScroll } = this.props;

        return (
            <HomeWrapper>
                <HomeLeft>
                    <img
                        className="banner-img"
                        src="https://upload.jianshu.io/admin_banners/web_images/4660/224da83c76e01d5deff07e163615921233af5c82.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/1250/h/540"
                    />
                    <Topic />
                    <List />
                </HomeLeft>
                <HomeRight>
                    <Recommend />
                    <Writer />
                </HomeRight>
                {showScroll && (
                    <BackTop onClick={this.handleScrollTop}>回到顶部</BackTop>
                )}
            </HomeWrapper>
        );
    }

    componentDidMount() {
        this.props.changeHomeData();
        this.bindEvents();
    }

    componentWillUnmount() {
        window.removeEventListener("scroll", this.props.changeScrollTopShow);
    }
}

const mapStateToProps = state => ({
    showScroll: state.getIn(["home", "showScroll"])
});

const mapDispatchToProps = dispatch => ({
    changeHomeData() {
        dispatch(actionCreators.getHomeInfo());
    },
    changeScrollTopShow() {
        const scrollTop = document.documentElement.scrollTop;
        if (scrollTop > 400) {
            dispatch(actionCreators.toggleTopShow(true));
        } else {
            dispatch(actionCreators.toggleTopShow(false));
        }
    }
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Home);
